package com.yingdong.handler;

import java.util.List;

import org.springframework.stereotype.Service;

import com.yingdong.annotation.NoCheckPlayer;
import com.yingdong.annotation.OpCode;
import com.yingdong.db.Account;
import com.yingdong.db.User;
import com.yingdong.logic.domain.GameUser;
import com.yingdong.logic.domain.QueueLoginInfo;
import com.yingdong.logic.service.OnlineService;
import com.yingdong.logic.service.SceneThreadService;
import com.yingdong.logic.service.UserService;
import com.yingdong.message.CreateRoleMessage;
import com.yingdong.message.DisconnectMessage;
import com.yingdong.message.LoginOkMessage;
import com.yingdong.message.UserInfoMessage;
import com.yingdong.opcode.ServerOpcode;
import com.yingdong.sceneserver.inner.message.RecvGameMessage;
import com.yingdong.sceneserver.net.GameUserSession;

@Service
public class LoginHandler {
	@NoCheckPlayer()
	@OpCode(id = ServerOpcode.LOGIN_OK)
	public static void handleLogin(GameUserSession session, RecvGameMessage msg) throws InterruptedException {
		session.setHandle(false);
		String userName = msg.readString();
		String password = msg.readString();
		OnlineService.loginQueue.put(new QueueLoginInfo(userName,password,session));
//		if (session.getContext().containsKey("accId")) {
//			int accId = (Integer) session.getContext().get("accId");
//			GameUser user = OnlineService.getGameUserByAccId(accId);
//			if (user != null) {
//				new DisconnectMessage().sendToClient(user.getSessionId());
//				return;
//			}
//		}
//		SceneThreadService.gameThreadPool.execute(new Runnable() {
//			public void run() {
//				try {
//					if (!session.isAlive()) {
//						return;
//					}
//					List<Account> list = Account.getInstance().selectObjectsByCondition("accName", userName);
//					if (list.size() == 0) {
//						Account account = new Account();
//						account.setAccName(userName);
//						account.setPassword(password);
//						account.setCreateDttm((int) (System.currentTimeMillis() / 1000));
//						Object index = account.saveToDB();
//						account.setId((Integer) index);
//						synchronized (session) {
//							if (!session.isAlive()) {
//								return;
//							}
//							session.getContext().put("accId", account.getId());
//							new LoginOkMessage(1, account.getId(), 0).sendToClient(session.getSessionId());
//						}
//					} else if (list.size() == 1) {
//						List<User> ulist = User.getInstance().selectObjectsByCondition("accId", list.get(0).getId());
//						synchronized (session) {
//							if (!session.isAlive()) {
//								return;
//							}
//							if (ulist.size() > 0)
//								new LoginOkMessage(1, list.get(0).getId(), ulist.get(0).getId()).sendToClient(session.getSessionId());
//							else {
//								new LoginOkMessage(1, list.get(0).getId(), 0).sendToClient(session.getSessionId());
//							}
//						}
//					} else {
//						new LoginOkMessage(2, 0, 0).sendToClient(session.getSessionId());
//					}
//					session.setActive(true);
//				} finally {
//					session.setHandle(true);
//				}
//			}
//		});

	}

	@NoCheckPlayer()
	@OpCode(id = ServerOpcode.CREATE_ROLE)
	public static void handleCreateRole(GameUserSession session, RecvGameMessage msg) {
		session.setHandle(false);
		if (!session.isActive())
			return;
		int accId = msg.readInt();
		String userName = msg.readString();
		int gender = msg.readByte();
		SceneThreadService.gameThreadPool.execute(new Runnable() {
			public void run() {
				try {
					if (!session.isAlive()) {
						return;
					}
					List<User> list = User.getInstance().selectObjectsByCondition("accId", accId);
					list = User.getInstance().selectObjectsByCondition("userName", userName);
					if (list.size() > 0) {
						new CreateRoleMessage(0, 2).sendToClient(session.getSessionId());

					} else {
						User usr = new User();
						usr.setAccId(accId);
						usr.setCreateDttm((int) (System.currentTimeMillis() / 1000));
						usr.setGender(gender);
						usr.setLastLoginDttm((int) (System.currentTimeMillis() / 1000));
						usr.setUserName(userName);
						int index = (Integer) usr.saveToDB();
						usr.setId(index);
						UserService.onUserCreated(index);
						new CreateRoleMessage(index, 1).sendToClient(session.getSessionId());
					}
				} finally {
					session.setHandle(true);
				}
			}
		});
	}

	@NoCheckPlayer()
	@OpCode(id = ServerOpcode.ENTER_SCENE)
	public static void handleEnterScene(GameUserSession session, RecvGameMessage msg) {
		session.setHandle(false);
		if (!session.isActive())
			return;
		int userId = msg.readInt();
		SceneThreadService.gameThreadPool.execute(new Runnable() {
			public void run() {
				try {
					if (!session.isAlive()) {
						return;
					}
					User user = User.getInstance().selectAllObjectsByKey(userId);
					if (user != null) {
						GameUser gameUser = new GameUser();
						gameUser.setSessionId(session.getSessionId());
						gameUser.setUserId(userId);
						gameUser.setUsr(user);
						gameUser.init();
						synchronized (session) {
							if (!session.isAlive()) {
								return;
							}
							session.getContext().put("gamePlayer", gameUser);
							OnlineService.putOline(gameUser);
						}

					}
					new UserInfoMessage(user).sendToClient(session.getSessionId());
				} finally {
					session.setHandle(true);
				}
			}
		});
	}

	@OpCode(id = ServerOpcode.READY)
	public static void handleReady(GameUserSession session, RecvGameMessage msg) {
		GameUser user = OnlineService.getGameUserInSession(session);
		user.firstEnter();
	}

}
